import { toHtml } from 'hast-util-to-html';
import { visit } from 'unist-util-visit';
import { addExport, isMdxJsxFlowElementHast } from '../../lib/index.js';
const langFilename = (className) => {
    switch (className) {
        case 'language-shell':
            return 'Bash';
        case 'language-json':
            return 'JSON';
        case 'language-js':
            return 'JavaScript';
        default:
            const language = className.substring(9);
            return language.charAt(0).toUpperCase() + language.slice(1);
    }
};
export const rehypeMdxExtractExamples = () => {
    return (tree) => {
        let request;
        let response;
        visit(tree, isMdxJsxFlowElementHast, (node, i, parent) => {
            if (node.name === 'RequestExample') {
                request = request !== null && request !== void 0 ? request : {
                    type: node.name,
                    children: parseChildren(node),
                };
                if (parent && i !== null)
                    parent.children.splice(i, 1);
            }
            else if (node.name === 'ResponseExample') {
                response = response !== null && response !== void 0 ? response : {
                    type: node.name,
                    children: parseChildren(node),
                };
                if (parent && i !== null)
                    parent.children.splice(i, 1);
            }
        });
        addExport(tree, 'codeExamples', { request, response });
        return tree;
    };
};
const parseChildren = (node) => {
    return node.children.filter(isMdxJsxFlowElementHast).flatMap((child) => {
        var _a, _b, _c;
        const preComponent = child.children[0];
        if ((preComponent === null || preComponent === void 0 ? void 0 : preComponent.type) !== 'element')
            return [];
        const html = toHtml(preComponent);
        let filename = Array.isArray((_a = preComponent.properties) === null || _a === void 0 ? void 0 : _a.className) &&
            typeof ((_b = preComponent.properties) === null || _b === void 0 ? void 0 : _b.className[0]) === 'string'
            ? langFilename(preComponent.properties.className[0])
            : '';
        if ('attributes' in child && typeof ((_c = child.attributes[0]) === null || _c === void 0 ? void 0 : _c.value) === 'string') {
            filename = child.attributes[0].value;
        }
        return [
            {
                filename,
                html,
            },
        ];
    });
};
